package org.thomias.autosave;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

public class SaveTask implements Runnable {

	@Override
	public void run() {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int min = cal.get(Calendar.MINUTE);

		String source = "test";
		String dest = "../../Oni-Cube";
		
		File srcFolder = new File(source);
		File destFolder = new File(dest + "/" + year + "." + format(month)
				+ "." + format(day) + "_" + format(hour) + "h" + format(min));

		if (!srcFolder.exists()) {
			System.out.println("Directory does not exist.");
			System.exit(0);
		} else {
			try {
				copy(srcFolder, destFolder);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("Done");
	}

	private String format(int nbr) {
		return (nbr > 9) ? "" + nbr : "0" + nbr;
	}

	private void copy(File src, File dest) throws Exception {
		if (src.isDirectory()) {
			if (!dest.exists()) {
				dest.mkdirs();
			}
			for (String file : src.list()) {
				File srcFile = new File(src, file);
				File destFile = new File(dest, file);
				copy(srcFile, destFile);
			}
		} else {
			InputStream in = new FileInputStream(src);
			OutputStream out = new FileOutputStream(dest);
			try {
				byte[] buffer = new byte[1024];
				int length;
				while ((length = in.read(buffer)) > 0) {
					out.write(buffer, 0, length);
				}
			} finally {
				in.close();
				out.close();
			}
		}
	}

}
